import React, { useState } from 'react';
import { Modal, Checkbox, Button, Space } from 'antd';
import type { CheckboxChangeEvent } from 'antd/es/checkbox';

export interface ProductColumnConfig {
  key: string;
  title: string;
  visible: boolean;
}

interface ProductColumnSettingModalProps {
  visible: boolean;
  onCancel: () => void;
  onOk: (columnConfigs: ProductColumnConfig[]) => void;
  columnConfigs: ProductColumnConfig[];
}

const ProductColumnSettingModal: React.FC<ProductColumnSettingModalProps> = ({
  visible,
  onCancel,
  onOk,
  columnConfigs,
}) => {
  const [localColumnConfigs, setLocalColumnConfigs] = useState<ProductColumnConfig[]>([]);

  // 当弹窗打开时，初始化本地状态
  React.useEffect(() => {
    if (visible) {
      setLocalColumnConfigs([...columnConfigs]);
    }
  }, [visible, columnConfigs]);

  const handleCheckboxChange = (key: string, e: CheckboxChangeEvent) => {
    const newConfigs = localColumnConfigs.map(config => {
      if (config.key === key) {
        return { ...config, visible: e.target.checked };
      }
      return config;
    });
    setLocalColumnConfigs(newConfigs);
  };

  const handleSelectAll = () => {
    const newConfigs = localColumnConfigs.map(config => ({
      ...config,
      visible: true,
    }));
    setLocalColumnConfigs(newConfigs);
  };

  const handleUnselectAll = () => {
    const newConfigs = localColumnConfigs.map(config => ({
      ...config,
      visible: false,
    }));
    setLocalColumnConfigs(newConfigs);
  };

  const handleOk = () => {
    onOk(localColumnConfigs);
  };

  return (
    <Modal
      title="选择商品表格列设置"
      visible={visible}
      onCancel={onCancel}
      onOk={handleOk}
    >
      <Space style={{ marginBottom: 16 }}>
        <Button size="small" onClick={handleSelectAll}>
          全选
        </Button>
        <Button size="small" onClick={handleUnselectAll}>
          全不选
        </Button>
      </Space>

      <div className="column-setting-list">
        {localColumnConfigs.map(config => (
          <div key={config.key} className="column-setting-item">
            <Checkbox
              checked={config.visible}
              onChange={e => handleCheckboxChange(config.key, e)}
            >
              {config.title}
            </Checkbox>
          </div>
        ))}
      </div>
    </Modal>
  );
};

export default ProductColumnSettingModal; 